import time
from pathlib import Path

from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.action_chains import ActionChains

urls = {
    'login': 'http://192.168.31.93/VZvipHtURf.php/index/login',
    'add': 'http://192.168.31.93/VZvipHtURf.php/category/add?dialog=1'
}

def waitxpath(driver, xpath):
    try:
        # 显示等待60秒
        WebDriverWait(driver, 60, 1).until(
            lambda x: x.find_element_by_xpath(xpath)
        )
    except Exception as e:
        raise e

def get_driver():
    '''获得浏览器驱动对象'''
    chromedriver = 'chromedriver'
    driver = webdriver.Chrome(executable_path=chromedriver)
    # 隐式等待
    driver.implicitly_wait(30)
    return driver

def login(driver):
    '''自动登录网站后台'''
    driver.get(urls['login'])

    username = driver.find_element_by_id('pd-form-username')
    username.clear() # 清空输入框中内容
    username.send_keys('admin')
    passwd = driver.find_element_by_id('pd-form-password')
    passwd.send_keys('admin123')
    captcha_xpath = '//*[@id="login-form"]/div[4]/input'
    waitxpath(driver, captcha_xpath)
    captcha = driver.find_element_by_xpath(captcha_xpath)
    _ = input('验证码：')
    captcha.send_keys(_) # 输入验证码
    # 点击登录按钮
    driver.find_element_by_xpath('//*[@id="login-form"]/div[6]/button').click()
    time.sleep(1)


def upload_image(driver):
    '''上传图片'''

    # 上传图片
    driver.find_element_by_id('c-image').send_keys('/Users/ayuliao/Desktop/山川.jpg')
    xpath = '//*[@id="p-image"]/li'
    waitxpath(driver, xpath) # 等待上传，图片上传成功，会有该元素

    # 无限循环，直到图片上传成功
    # while True:
    #     try:
    #         driver.find_element_by_xpath(xpath)
    #         break
    #     except:
    #         pass

def select(driver):
    '''选择下拉框'''
    # 标志
    mark_xpath = '//*[@id="add-form"]/div[6]/div/div/button/span[1]'
    mark = driver.find_element_by_xpath(mark_xpath)
    # 将鼠标移动到mark元素上执行点击操作
    ActionChains(driver).move_to_element(mark).click(mark).perform()
    # 标志 - 首页
    mark_index_xpath = '//*[@id="add-form"]/div[6]/div/div/div/ul/li[2]'
    mark_index = driver.find_element_by_xpath(mark_index_xpath)
    # 选择下拉框中的首页
    ActionChains(driver).move_to_element(mark_index).click(mark_index).perform()

def create_classify(driver):
    '''创建分类'''
    driver.get(urls['add'])
    driver.find_element_by_id('c-name').send_keys('测试分类') # 名称
    driver.find_element_by_id('c-nickname').send_keys('测试分类的昵称') # 昵称
    select(driver) # 选择下拉框
    # upload_image(driver) # 上传图片
    # 点击确定按钮
    button_xpath = '//*[@id="add-form"]/div[12]/div/button[1]'
    driver.find_element_by_xpath(button_xpath).click()

def clear(driver):
    # 清空所有cookie
    driver.delete_all_cookies()
    # 退出浏览器
    driver.quit()

def screenshot(driver):
    '''
    保存截图
    '''
    dir = Path('screenshot')
    if not dir.is_dir():
        dir.mkdir(parents=True)
    now = str(int(time.time()))
    imgpath = dir.joinpath(f'{now}.png')
    driver.save_screenshot(str(imgpath))

def main():
    driver = get_driver()
    login(driver)
    create_classify(driver)
    screenshot(driver)
    clear(driver)

main()